<?php

App::uses('AppHelper', 'View/Helper');

/**
 * Description of UploadHelper
 *
 * @author jarrod
 */
class UploadHelper extends AppHelper {

    public $helpers = array('Html');

    /**
     * Set Ajax upload field in "add" view.
     * It uses HTML5 features to upload files. On older browsers it will not work.
     * 
     * @param type $result_input_id Input field ID to fill up image name value in.
     * @param type $options <b>'path'</b> to set custom path relative to 'webroot'. 
     *      If path starts with '/' it will be absotule to filesystem. 
     *      Default to 'webroot/files'
     *  <b>"multiple"</b> if boolean true uploader handle multiple files. Default to false.
     * @throws Exception 
     */
    public function add($result_input_id, $options = array()) {
        if (!$result_input_id) {
            throw new Exception("Set upload input ID");
        }
        
        require_once(ROOT . DS . APP_DIR . '/Plugin/GdgUpload/Config/Config.php');

        if (isset($options['path'])) {
            $path = $options['path'];
        }

        if ($path == null) {
            $path = Configure::read('gdg.upload.defaults.directory');
        }
        $multiple = false;
        if (isset($options['multiple']) && $options['multiple'] === true) {
            $multiple = $options['multiple'];
        }
        
        $action = Router::url(array('controller' => 'upload', 'action' => 'upload', 'plugin' => 'gdg_upload', 'admin'=>false));
        $this->Html->css('/gdg_upload/css/style.css', null, array('inline' => false));
        $this->Html->script('GdgUpload.uploader.js', array('inline' => false, 'block' => 'scriptBottom'));

        $fileFieldId = 'gdgupload_' . $result_input_id;
        $options = array(
            'field' => $result_input_id,
            'path' => $path,
            'app' => $action,
            'fileid' => $fileFieldId
        );
        $str = 'if(!window.gdguploadoptions) window.gdguploadoptions = []; ';
        $str .= 'window.gdguploadoptions[window.gdguploadoptions.length] = ' . json_encode($options) . ';';
        echo $this->Html->scriptBlock($str);

        $str = '<input type="file" id="' . $fileFieldId . '" style="display:none;"';
        if($multiple){
            $str .= ' multiple="true"';
        }
        $str .= '/>';
        echo $str;
    }

    public function edit() {
        
    }

}

?>